<template>
  <div class="article-add">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span> {{ ruleForm.id ? "修改" : "发表" }}文章 </span>
          <el-button type="primary" link @click="router.go(-1)">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            style="width: 100%"
            v-model="ruleForm.cate_id"
            class="m-2"
            placeholder="请选择文章分类"
          >
            <el-option
              v-for="item in selectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <VueEditor
            v-model="ruleForm.content"
            @text-change="vueEditorChange"
          ></VueEditor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <div class="cover-img-box">
            <img
              v-if="ruleForm.cover_img"
              ref="imgRef"
              :src="ruleForm.cover_img"
              alt=""
            />
            <img
              v-if="!ruleForm.cover_img"
              src="../assets/images/cover.jfif"
              alt=""
            />
            <input
              ref="iptFileRef"
              type="file"
              style="display: none"
              @change="getFile"
            />
            <p>注意: 图片大小不能超过2M</p>
            <el-button type="success" @click="selCoverFn">+ 选择封面</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            {{ ruleForm.id ? "修改" : "发布" }}
          </el-button>
          <el-button v-if="!ruleForm.id" @click="resetForm(ruleFormRef)">
            存为草稿
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, getCurrentInstance } from "vue";
import store from "../store";
import { VueEditor } from "vue3-editor";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import qs from "qs";
import { articleCatesRequest } from "../api/article";
import { addArticleRequest, updateArticleRequest } from "../api/article.js";
// 标签和样式用, 引入图片可以写路径, JS中引入图片需要import引入
// webpack会把图片变为一个base64字符串或在打包后的图片临时路径
import coverImg from "../assets/images/cover.jfif";

const router = useRouter();
const route = useRoute();
const instance = getCurrentInstance();
const imgRef = ref();
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  id: "",
  title: "",
  cate_id: "",
  content: "",
  cover_img: "",
  state: "",
});
// 富文本编辑器校验规则
const contentRule = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("文章内容不能为空!"));
  } else {
    callback();
  }
};
const rules = reactive({
  title: [
    {
      required: true,
      message: "文章标题是必填项!",
      trigger: "blur",
    },
  ],
  cate_id: [
    {
      required: true,
      message: "文章分类是必选项!",
      trigger: "change",
    },
  ],
  content: [
    {
      validator: contentRule,
      trigger: "change",
    },
  ],
  cover_img: [
    {
      required: false,
      message: "文章封面不能为空!",
      trigger: "change",
    },
  ],
});
const selectList = ref([]);

console.log("author_id", store.state.userinfo.id);
console.log("路由传参", history.state);
if (history.state.id) {
  ruleForm.id = history.state.id;
  ruleForm.title = history.state.title;
  ruleForm.cate_id = history.state.cate_id;
  ruleForm.content = history.state.content;
  ruleForm.cover_img = history.state.cover_img;
  ruleForm.state = history.state.state;
}

// 富文本编辑器内容改变事件
const vueEditorChange = () => {
  instance?.refs.ruleFormRef.validateField("content");
};
// 发布文章请求
const publishArticle = async (state = "已发布") => {
  const params = qs.stringify({
    title: ruleForm.title,
    cate_id: ruleForm.cate_id,
    content: ruleForm.content,
    cover_img: ruleForm.cover_img,
    state,
    author_id: store.state.userinfo.id,
    author_name: store.state.userinfo.username,
  });
  const { data: res } = await addArticleRequest(params);
  // console.log('发布文章请求', res)
  const { status, message } = res;
  if (status !== 0) return ElMessage.error(message);
  ElMessage.success(message);
};
// 修改文章请求
const updateArticle = async (state = "已发布") => {
  const params = qs.stringify({
    id: ruleForm.id,
    title: ruleForm.title,
    cate_id: ruleForm.cate_id,
    content: ruleForm.content,
    cover_img: ruleForm.cover_img,
    state,
    author_id: store.state.userinfo.id,
    author_name: store.state.userinfo.username,
  });
  const { data: res } = await updateArticleRequest(params);
  // console.log('更新文章请求', res)
  const { status, message } = res;
  if (status !== 0) return ElMessage.error(message);
  ElMessage.success(message);
};
// 发布按钮事件
const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (ruleForm.id) {
        updateArticle();
      } else {
        publishArticle();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 存为草稿
const resetForm = async formEl => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      publishArticle((stats = "草稿"));
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 选择封面的点击事件
const selCoverFn = () => {
  // 固定写法
  instance?.refs.iptFileRef.click();
};
// 用户选择了封面图片文件
const getFile = e => {
  const files = e.target.files;
  if (files.length === 0) {
    // 用户没有选择图片, 把图片属性置空
    ruleForm.cover_img = "";
    // 显示默认图片
    instance?.refs.imgRef.setAttribute("src", coverImg);
  } else {
    // 用户选择了图片, 把文件直接保存到表单对象的属性里
    // ruleForm.cover_img = files[0]
    // 将图片文件 -> base64字符串 发送给后端
    // 1. 创建 FileReader 对象
    const fr = new FileReader();
    // 2. 调用 readAsDataURL 函数, 读取文件内容
    fr.readAsDataURL(files[0]);
    // 3. 监听 fr 的 onload 事件
    fr.onload = e => {
      // 4. 通过 e.target.result 获取到读取的结果, 值是字符串(base64 格式的字符串)
      ruleForm.cover_img = e.target.result;
    };

    // 把图片文件, 显示在img标签里, 采用url方法
    const url = URL.createObjectURL(files[0]);
    instance?.refs.imgRef.setAttribute("src", url);
  }
  // 校验具体某个表单字段
  instance?.refs.ruleFormRef.validateField("cover_img");
};
// 获取文章分类数据
const getarticleCatesRequest = async () => {
  const { data: res } = await articleCatesRequest();
  const { status, message, data } = res;
  if (status !== 0) ElMessage.error(message);
  selectList.value = data;
};
getarticleCatesRequest();
</script>

<style lang="scss" scoped>
.el-upload-list__item-thumbnail {
  width: 100%;
}

.cover-img-box {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  img {
    width: 480px;
  }

  p {
    font-size: 12px;
  }
}

.quillWrapper {
  width: 100%;
}
</style>
